package club.jdiy.admin.context;


import club.jdiy.core.cache.CacheType;
import club.jdiy.core.properties.JDiyProperties;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Component
@WebFilter("/*")
public class ClusterFilter implements Filter {

    private static final Set<String> excludePaths = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/static/", "/uploads/")
    ));

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        if (jDiyProperties.getCache().getType() == CacheType.none) {//当未使用缓存时，则不开启分布式会话
            chain.doFilter(req, res);
            return;
        }

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getRequestURI().substring(request.getContextPath().length());
        boolean skip = false;
        for (String s : excludePaths) {
            if (path.startsWith(s)) {
                skip = true;
                break;
            }
        }

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);


        if (skip) chain.doFilter(req, res);
        else chain.doFilter(new ClusterRequest(request, response), response);
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @javax.annotation.Resource
    private JDiyProperties jDiyProperties;
}

